const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const fs = require('fs');
const path = require('path');
const { binaryFragmentation } = require('nodejs-websocket/Connection');


var userList = [];

const io = new Server(server, {
    cors: {
      origin: "*",
      methods: ["GET", "POST"]
    },
    maxHttpBufferSize: 4e6 // 4Mb

});

app.get('/', (req, res) => {
  res.redirect('/index.html')
});


io.engine.on("connection_error", (err) => {
  console.log(err.req);      // the request object
  console.log(err.code);     // the error code, for example 1
  console.log(err.message);  // the error message, for example "Session ID unknown"
  console.log(err.context);  // some additional error context
});


io.on('connection', (socket) => {
  console.log('a user connected');
 
  // {type: "system" ,content:"123加入了群聊" , time: "2023-01-01 15:23" , from: "123" ,fromavatar:"http://localhost:5173/assets/images/avatar01.jpg", to:"all"},
  // {type: "talk" ,content:"你好" , time: "2023-01-01 15:23" , from: "srx" ,fromavatar:"http://localhost:5173/assets/images/avatar02.jpg", to:"all"},
  

  socket.on("login",data=>{ // data {username,avata}
    // 服务端处理login请求
    console.log("begin  login.",userList,data);

    // 设置该socket的username 
    socket.username = data.username;
    console.log("socket.username= "+socket.username);
    // data.username;
    var ret = userList.some(item=>{
      if(item.username == (data.username)){
        return true;
      }
    });
    if(ret==false){
      // add to userlist
      userList.push(data);// {username,avata}

      /**
       * 这个并没有推送所有的已经登陆的用户，而仅仅是session对应的用户才收到该消息。
       */
      socket.emit("loginSuccess",data); // 只回传最新的userList
      io.emit('userListChanged',{"userList":userList,"newUser":data});

    }else{
      // login in already.
      socket.emit("noneed2login",{userList,data}); // data is {username,avata}
    }

    console.log("end  login.",userList,data);
  });

  // 断开连接后群发消息
  socket.on("disconnect",()=>{

     console.log("disconnect!!!!!!");

    console.log("removeMe socket.usernmae="+socket.username);
    var index = userList.some((usr,i)=>{
      if(usr.username == socket.username){
        return i;
      }
    });
    if(index != -1 ){
      userList.splice(index,1);//删除该用户
    }
    console.log("after removeMe userlist=",userList);
    io.emit("someoneDisconnect",userList);
    
  })

  // 处理前端发送的图片
  socket.on("sendImage",obj=>{
    console.log("client send image to server");
    io.emit("broadcaseImageToClients",obj);
  })

  // test for Big jpg. read by Server pass to client
  socket.on("getBigImage",()=>{
    console.log("__dirname="+__dirname);
    console.log(",path.resolve(__dirname="+path.resolve(__dirname));
    console.log("111",path.resolve(__dirname,'./big/WechatIMG395.jpeg'));
    // var readStream = fs.createReadStream(path.resolve(__dirname,'./big/WechatIMG395.jpeg'),
    var readStream = fs.createReadStream(path.resolve(__dirname,'./big/avatar.jpg'),
      {
        encoding:"binary"
      });
    var chunks = [];
    readStream.on("readable",function(){
      console.log("image loading");
    });
    var i=0;
    readStream.on("data",function(chunk){
      console.log("data",i++);
      chunks.push(chunk);
      socket.emit("img-chunk",chunk);
    });
    readStream.on("end",function(){
      console.log("image loaded");
    })
    
  })

  // 处理前端发送的文字
  socket.on("sendMsgToServer",obj=>{
    //var obj = {type:"talk",content:textarea.value.textContent,from:username.value,to:"all"} // 暂定群聊
    io.emit("broadcaseMsgToClients",obj);
  })
});




server.listen(3000, () => {

  console.log('listening on *:3000');
});

